﻿from flask import Flask, g, render_template, request,flash,redirect,url_for,Blueprint
import pymysql,json,datetime,json
from .login.login import *
from .setting import *
printsql=True
printrequestdata=True
from flask_cors import CORS
config_blue = Blueprint('config',__name__)


def json_encoder(obj):
    if isinstance(obj, datetime.datetime):
        return obj.strftime("%Y-%m-%d %X")
    elif isinstance(obj, datetime.date):
        return obj.strftime("%Y-%m-%d")
@config_blue.route('/sys/config/list')
# @login_required
def configlist():
	if request.args.get('paramKey'):like = request.args.get('paramKey')
	else:like=''
	if request.args.get('page'):page = request.args.get('page')
	else:page=1
	if request.args.get('limit'):limit = request.args.get('limit')
	else:limit=10
	# print(like,page,limit)
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_config WHERE  param_key LIKE '%"+like+"%'  LIMIT "+str(limit) +" OFFSET " +str((int(page)-1)*int(limit))
	sqlcount = "SELECT count(*) from sys_config  WHERE  param_key LIKE '%"+like+"%'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'id':dataList1[i][0],'paramKey':dataList1[i][1],'paramValue':dataList1[i][2],'status':dataList1[i][3],'remark':dataList1[i][4]})
		cursor.execute(sqlcount)
		count = cursor.fetchall()[0][0]
	except Exception as e:
		return "Error: unable to fetch data from sys_config"+str(e)
	db.close()
	data={
			'msg': 'success',
			'code': 0,
			'page': {
				'totalCount': len(dataList),
				'pageSize': 10,
				'totalPage': 1,
				'currPage': 1,
				'list': dataList
				}
			}
	return json.dumps(data,default=json_encoder)
@config_blue.route('/sys/config/save',methods=['POST'])
# @login_required
def configsave():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'paramKey' in d.keys():paramKey = d['paramKey']
		else:paramKey=''
		if 'paramValue' in d.keys():paramValue = d['paramValue']
		else:paramValue=''
		if 'status' in d.keys():status = d['status']
		else:status=''
		if 'remark' in d.keys():remark = d['remark']
		else:remark=''
	elif request.form:
		paramKey = request.form['paramKey']
		paramValue = request.form['paramValue']
		status = request.form['status']
		remark = request.form['remark']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = 'insert into sys_config (param_key,param_value,status,remark) values('+"'"+str(paramKey)+"',"+"'"+str(paramValue)+"',"+"'"+str(status)+"',"+"'"+str(remark)+"')"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to save data from sys_config"+str(e)
	db.close()
	
	data={
      'msg': 'success',
      'code': 0
    }
	return json.dumps(data,default=json_encoder)
@config_blue.route('/sys/config/update',methods=['POST'])
# @login_required
def configupdate():
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'id' in d.keys():id = d['id']
		else:id=''
		if 'paramKey' in d.keys():paramKey = d['paramKey']
		else:paramKey=''
		if 'paramValue' in d.keys():paramValue = d['paramValue']
		else:paramValue=''
		if 'status' in d.keys():status = d['status']
		else:status=''
		if 'remark' in d.keys():remark = d['remark']
		else:remark=''
	elif request.form:
		id = request.form['id']
		paramKey = request.form['paramKey']
		paramValue = request.form['paramValue']
		status = request.form['status']
		remark = request.form['remark']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	cursor = db.cursor()
	sql ="UPDATE sys_config SET param_key='"+str(paramKey)+"',param_value='"+str(paramValue)+"',status='"+str(status)+"',remark='"+str(remark)+"'"+ "WHERE id = '"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_config"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@config_blue.route('/sys/config/delete',methods=['POST'])
# @login_required
def configdelete():
	# print("content_type:", request.headers.get("content_type"))
	# print("data:", request.data)
	# print("data:", str(request.data, 'UTF-8'))
	# print("form:", request.form)
	# print("files:", request.files)
	if request.data:
		if printrequestdata:print(request.data)
		d=json.loads(str(request.data, 'UTF-8'))
		if 'id' in d.keys():id = d['id']
		else:id=''
	elif request.form:
		id = request.form['id']

	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="DELETE FROM sys_config WHERE id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		db.commit()
	except Exception as e:
		db.rollback()
		return "Error: unable to delete data from sys_config"+str(e)
	db.close()

	data={
	  'msg': 'success',
	  'code': 0
	}
	return json.dumps(data,default=json_encoder)
@config_blue.route('/sys/config/info')
@config_blue.route('/sys/config/info/<id>')#for update
# @login_required
def configinfo(id=None):
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql ="SELECT * from sys_config where  id='"+str(id)+"'"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList:
			# print(row)
		config={'id':dataList1[0][0],'paramKey':dataList1[0][1],'paramValue':dataList1[0][2],'status':dataList1[0][3],'remark':dataList1[0][4]}
		data={
				'msg': 'success',
				'code': 0,
				'config': config
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_config"+str(e)
	db.close()
@config_blue.route('/sys/config/select') #for other talbe's selector
# @login_required
def configselect():
	db = pymysql.connect(host=dbhost,user=dbuser,password=dbpassword,database=dbdatabase)
	cursor = db.cursor()
	sql = "SELECT * from sys_config"
	if printsql:print(sql)
	try:
		cursor.execute(sql)
		dataList1 = cursor.fetchall()
		# for row in dataList1:
			# print(row)
		dataList=[]
		for i in range(len(dataList1)):
			dataList.append({'id':dataList1[i][0],'paramKey':dataList1[i][1],'paramValue':dataList1[i][2],'status':dataList1[i][3],'remark':dataList1[i][4]})
		# print(dataList)
		data={
				'msg': 'success',
				'code': 0,
				'list': dataList
				}
		return json.dumps(data,default=json_encoder)
	except Exception as e:
		return "Error: unable to fetch data from sys_role"+str(e)
	db.close()	
	
	
	


